package com.wsoft.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.core.exception.Asserts;
import com.wsoft.system.entity.SysPostEntity;
import com.wsoft.system.entity.SysResourceCategoryEntity;
import com.wsoft.system.mapper.SysResourceCategoryMapper;
import com.wsoft.system.query.resourse.category.CategoryInsertQuery;
import com.wsoft.system.query.resourse.category.CategoryListQuery;
import com.wsoft.system.query.resourse.category.CategoryUpdateQuery;
import com.wsoft.system.service.ISysResourceCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 资源分类表 服务实现类
 * </p>
 *
 * @author juiet
 * @since 2024年11月18日 17:14:14
 */
@Service
public class SysResourceCategoryServiceImpl extends ServiceImpl<SysResourceCategoryMapper, SysResourceCategoryEntity> implements ISysResourceCategoryService {

    @Override
    public boolean insert(CategoryInsertQuery query) {
        SysResourceCategoryEntity entity = Convert.convert(SysResourceCategoryEntity.class, query);
        QueryWrapper<SysResourceCategoryEntity> categoryWrapper =  new QueryWrapper<>();
        categoryWrapper.lambda().eq(SysResourceCategoryEntity::getName, entity.getName());
        if (count(categoryWrapper) > 0) {
            Asserts.fail("[sys.name.exist]");
        }
        return save(entity);
    }

    @Override
    public boolean update(CategoryUpdateQuery query) {
        SysResourceCategoryEntity entity = Convert.convert(SysResourceCategoryEntity.class, query);
        QueryWrapper<SysResourceCategoryEntity> categoryWrapper =  new QueryWrapper<>();
        categoryWrapper.lambda().eq(SysResourceCategoryEntity::getName, entity.getName())
                .ne(SysResourceCategoryEntity::getId, entity.getId());
        if (count(categoryWrapper) > 0) {
            Asserts.fail("[sys.name.exist]");
        }
        return updateById(entity);
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public SysResourceCategoryEntity getCategory(Long id) {
        return getById(id);
    }

    @Override
    public PageInfo<SysResourceCategoryEntity> pageCategory(CategoryListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        QueryWrapper<SysResourceCategoryEntity> categoryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(query.getName())) {
            categoryWrapper.lambda().like(SysResourceCategoryEntity::getName, query.getName());
        }
        return PageInfo.of(list(categoryWrapper));
    }
}
